package com.lenovo.dao.impl;

import com.lenovo.dao.EmpDao;
import com.lenovo.pojo.*;
import com.lenovo.util.DBUtil;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class EmpDaoImpl implements EmpDao {
    DBUtil util = new DBUtil();
    @Override
    public Result login(String account, String password) throws SQLException {
        String sql = "SELECT " +
                        "e.*,r.`name` rolename,d.`name` deptname " +
                        "from " +
                        "emp e,role r,deptment d " +
                        "WHERE " +
                         "e.account=? and e.password = ? and e.roleid = r.id and e.deptid=d.id";
        List<Object> params = new ArrayList<>();
        params.add(account);
        params.add(password);
        ResultSet set = util.executeQuery(sql, params);
        Emp emp=new Emp();
        Result result = new Result(402,"用户名或密码错误");
        while(set.next()){
            int id = set.getInt(1);
            String name = set.getString(2);
            double salary=set.getDouble(5);
            int sex = set.getInt(6);
            String phone = set.getString(7);
            String email=set.getString(8);
            int deptid = set.getInt(9);
            int roleid = set.getInt(10);
            String rolename=set.getString(11);
            String deptname=set.getString(12);
            Deptment deptment=new Deptment(deptid,deptname); //部门
            Role role = new Role(roleid,rolename);

            emp.setId(id);
            emp.setName(name);
            emp.setSalary(salary);
            emp.setSex(sex);
            emp.setPhone(phone);
            emp.setEmail(email);
            emp.setAccount(account);
            emp.setPassword(password);
            emp.setDeptment(deptment);
            emp.setRole(role);

            result.setCode(200);
            result.setMsg("登录成功");
            result.setResult(emp);
        }

        return result;
    }

    @Override
    public Result showMenuByEmp(int roleid) throws SQLException {
        String sql = "SELECT rp.permissionid ,p.name FROM role_permission rp , permission p " +
                "where roleid= "+roleid+" AND p.id = rp.permissionid";
        ResultSet set = util.executeQuery(sql, null);
        List<Permission> list = new ArrayList<>();
        Result result = new Result(400,"查询失败！");
        while (set.next()){
            int id = set.getInt(1);
            String permNmae = set.getString(2);
            Permission permission=new Permission(id,permNmae);
            list.add(permission);
            result.setCode(200);
            result.setMsg("查询成功");
            result.setResult(list);
        }
        return result;
    }
}
